<template>
  <div class="container">
    <div class="tabs-lb">
      <span>测试验证</span>
      <button class="btn_operation_add" @click="$router.back()">返回</button>
      <!-- <button @click="$router.push('/signGuide')" class="btn_operation_add">签名指南</button> -->
    </div>
    <!-- <div class="sfzsb">
      <div class="title">安全认证</div>
      <div class="item">
        <span>密钥：</span>
        <el-select v-model="ak" style="width: 100%" @change="myChange">
          <el-option
            v-for="(item, index) in myList"
            :key="index"
            :label="item.myms"
            :value="item.ak"
          >
          </el-option>
        </el-select>
      </div>
    </div>-->
    <div class="nlxq">
      <div class="title">请求参数</div>
      <div
        style="margin-top:15px;padding:10px;border:1px solid #ccc"
        v-for="(item,index) in nlxq"
        :key="index"
      >
        <div class="group-title">
          <span class="ml10">安全认证</span>
        </div>
        <div v-if="isShowList.cationShow" class="secure-cation">
          <div class="item">
            <span>ak</span>
            <el-input v-model="ak" :readonly="true"></el-input>
          </div>
          <div class="item">
            <span>sk</span>
            <el-input v-model="sk" :readonly="true"></el-input>
          </div>
        </div>
        <template v-if="item.urlList.length">
          <div class="group-title">
            <span class="ml10">请求参数(URL)</span>
          </div>
          <!-- :model="urlForm" -->
          <el-form label-width="140px">
            <el-form-item
              style="width:100%"
              v-for="(urlItem,index) in item.urlList"
              :key="index"
              :label="urlItem.cs"
            >
              <input style="width:100%" class="inputStyle" v-model="urlItem.zh" />
            </el-form-item>
          </el-form>
        </template>
        <template v-if="item.headerList.length">
          <div class="group-title">
            <span class="ml10">请求参数(HEADER)</span>
          </div>
          <el-form label-width="140px">
            <el-form-item
              v-for="headerItem in item.headerList"
              :key="headerItem.id"
              :label="headerItem.cs"
            >
              <el-input v-model="headerItem.zh" :readonly="headerItem.readonly"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template v-if="item.bodyList.length">
          <div class="group-title">
            <span class="ml10">请求参数(BODY)</span>
          </div>
          <el-form label-width="140px" ref="bodyRef">
            <el-form-item v-for="bodyItem in item.bodyList" :key="bodyItem.id" :label="bodyItem.cs">
              <input class="inputStyle" v-model="bodyItem.mrz" style="width:50% " />
              <div class="itemMs" v-if="bodyItem.sm">
                <img src="~@/assets/img/grzx/疑问.png" alt />
                <span>{{bodyItem.sm}}</span>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </div>
      <div class="btn-ts" style="margin-top:15px">
        <el-button type="success" @click="tsData">调试</el-button>
      </div>
      <div class="title">请求结果</div>
      <pre class="pre" v-html="tsjg"></pre>
    </div>
  </div>
</template>
<script>
import jkglService from '@/api/jkgl'
import myglService from '@/api/mygl'
import axios from 'axios'
import { getSign } from '@/utils/sign.js'
export default {
  data() {
    return {
      jkbh: '',
      urlForm: {},
      headerForm: {},
      bodyForm: {},
      // 配置请求参数
      urlList: [],
      headerList: [
        { readonly: true, id: 'appId', zh: '', cs: 'appId' },
        { readonly: true, id: 'ts', zh: '', cs: 'ts' },
        { readonly: true, id: 'sign', zh: '', cs: 'sign' }
      ],
      bodyList: [],
      nlxq: [],
      tsjg: '',
      ak: '',
      sk: '',
      myList: [],
      // 规则校验
      bodyRole: {},
      isShowList: {
        urlShow: true,
        headerShow: true,
        bodyShow: true,
        cationShow: true,
      },

      ceshiList: []
    }
  },
  mounted() {
    // 获取路由信息
    this.getRouter()
    // 获取安全认证表格
    this.getAqrzList()

  },
  watch: {

  },
  methods: {
    /* 获取路由信息 */
    async getRouter() {
      if (this.$route.query.cs) {
        JSON.parse(this.$route.query.cs).cells.forEach(item => {
          if (item.data && item.data.jkbh) {
            this.jkbh = item.data.jkbh;
            this.ceshiList.push(
              new Promise((resolve, reject) => {
                const params = {
                  jkbh: this.jkbh
                }
                jkglService
                  .getJkdy(params)
                  .then(res => {
                    resolve(res)
                  }).catch(error => {
                    !error.isError &&
                      this.$message({ type: "warning", message: error.message });
                  })
              })
            )
          }
        })
        Promise.all(this.ceshiList).then(res => {
          //这里的list则是页面渲染的内容
          this.nlxq = res;
          this.getFormList(this.nlxq)
        })
      }
    },
    /*
     * 获取安全认证表格
     */
    getAqrzList() {
      const params = {
        filter: {
          myms: '',
          myzt: '已启用'
        },
        orderBy: '',
        pageNum: 1,
        pageSize: 100
      }
      myglService
        .queryMy(params)
        .then(res => {
          this.myList = res.list || []
          this.ak = res.list[0]?.ak;
          this.sk = res.list[0]?.sk;
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
    },
    myChange() {
      this.sk = this.myList.find(item => item.ak == this.ak).sk
    },

    /*
     * 获取调试信息
     */
    getNlxq() {
      const params = {
        jkbh: this.jkbh
      }
      jkglService
        .getJkdy(params)
        .then(res => {
          // 组装请求参数
          console.log(res);
          // this.nlxq.push(res);
          // console.log(this.nlxq);
          // this.nlxq.forEach(item => {
          //   this.getFormList(item)
          // })
        }).catch(error => {
          !error.isError &&
            this.$message({ type: "warning", message: error.message });
        })


    },

    /* 获取表单 */
    getFormList(resList) {
      resList.forEach(item => {
        item['urlList'] = JSON.parse(item.urlcs);
        item['headerList'] = [...this.headerList, ...JSON.parse(item.headercs)];
        item['bodyList'] = JSON.parse(item.qqcs);
        this.headerList = [...this.headerList, ...JSON.parse(item.headercs)];
        // this.bodyList.push(JSON.parse(item.qqcs))
        // this.urlList.push(JSON.parse(item.urlcs))
      })
      this.bodyForm = {}
      // this.bodyList.forEach(item => {
      //   item.forEach(item => {
      //     this.$set(this.bodyForm, item.cs, item.mrz);
      //     this.bodyRole[item.cs] = [{ required: true, message: '请输入内容', trigger: 'blur' }];
      //     if (item.sfbx === 'Y') {
      //       this.bodyRole[item.cs][0].required = true
      //     } else {
      //       this.bodyRole[item.cs][0].required = false
      //     }
      //   })
      // })
    },
    ShowClike(data) {
      if (data === 'url') {
        this.isShowList.urlShow = !this.isShowList.urlShow;
        return
      }

      if (data === 'header') {
        this.isShowList.headerShow = !this.isShowList.headerShow;
        return
      }

      if (data === 'body') {
        this.isShowList.bodyShow = !this.isShowList.bodyShow;
        return
      }

      if (data === 'cation') {
        this.isShowList.cationShow = !this.isShowList.cationShow;
        return
      }
    },
    noneClike(data) {
      if (data === 'url') {
        this.isShowList.urlShow = !this.isShowList.urlShow;
        return
      }

      if (data === 'header') {
        this.isShowList.headerShow = !this.isShowList.headerShow;
        return
      }

      if (data === 'body') {
        this.isShowList.bodyShow = !this.isShowList.bodyShow;
        return
      }

      if (data === 'cation') {
        this.isShowList.cationShow = !this.isShowList.cationShow;
        return
      }
    },

    /*
     * 调试
     */
    async tsData() {
      // 设置默认token
      const token = window.sessionStorage.getItem('token')
      axios.defaults.headers['tf_token'] = token || ''
      // 签名
      // appId
      const appId = this.headerList.find(item => item.cs === 'appId')
      appId.zh = this.ak
      // ts
      const ts = this.headerList.find(item => item.cs === 'ts')
      ts.zh = new Date().getTime()
      // sign
      const sign = this.headerList.find(item => item.cs === 'sign')
      sign.zh = getSign(this.ak, this.sk, ts.zh)

      let url = '';
      let params = {}


      for (let i = 0; i < this.nlxq.length; i++) {
        for (let el of this.nlxq[i].bodyList) {
          params[el.cs] = el.mrz
        }
      }

      let toRes = {}
      for (let i = 0; i < this.nlxq.length; i++) {
        url = this.nlxq[i].bldz;
        if (this.nlxq[i].urlList && this.nlxq[i].urlList.length > 0) {
          this.nlxq[i].urlList.forEach(item => {
            url = url + `${url.split('?').length > 1 ? '&' : '?'}${item.cs}=${item.zh}`
          })
        }
        if (this.nlxq[i].qqfs === 'POST') {
          toRes = await axios.post(url, { ...params, appId: appId.zh })
        } else {
          toRes = await axios.get(url, { ...params, appId: appId.zh })
        }
      }

      for (let el of this.headerList) {
        axios.defaults.headers[el.cs] = el.zh
      }
      // if (this.nlxq[this.nlxq?.length - 1].qqfs === 'POST') {
      //   res = await axios.post(url, this.bodyForm)
      // } else {
      //   res = await axios.get(url, this.bodyForm)
      // }
      this.tsjg = JSON.stringify(toRes.status ? toRes.data : toRes, null, 4)
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  .sfzsb {
    margin-top: 20px;
    width: 100%;
    padding: 40px 30px;
    background: #fff;
    border: solid 1px #cecece;
    .title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }
  }
  .nlxq {
    margin-top: 20px;
    width: 100%;
    padding: 40px 30px;
    background: #fff;
    border: solid 1px #cecece;

    .title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }

    .btn-ts {
      width: 100%;
      height: 40px;
      text-align: center;
    }
    .pre {
      width: 100%;
      height: 300px;
      border: solid 1px #cecece;
      overflow: auto;
      margin-top: 20px;
    }
  }
}
.signGuide {
  font-size: 20px;
  margin-left: 10px;
  cursor: pointer;
}

.secure-cation {
  display: flex;
  width: 100%;
  background: #fff;
  padding-bottom: 10px;
  .item {
    width: 50%;
    display: flex;
    align-items: center;
    // margin-top: 20px;
    > span {
      display: inline-block;
      width: 170px;
      text-align: right;
      padding-right: 10px;
    }
  }
}

.itemMs {
  display: inline-block;
  margin-left: 10px;
  width: 49%;
  word-break: break-all;
  span {
    margin-left: 5px;
  }
}

::v-deep .el-form-item__content {
  line-height: 15px;
}

.group-title {
  width: 100%;
  height: 50px;
  line-height: 50px;
  float: left;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 10px;
  span {
    position: relative;
    margin-left: 15px;
    color: #333333;
    font-weight: bold;
  }
  span:before {
    content: "";
    position: absolute;
    top: 3px;
    left: -9px;
    width: 4px;
    height: 18px;
    background-color: #0e69ff;
  }
}

.inputStyle {
  outline: none;
  height: 34px !important;
  border-radius: 3px;
  border: 1px solid #c0c4cc;
  color: #4f5e7b;
  padding: 0 10px;
  font-size: 16px;
}
</style>
